/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bumblebee.sessions;

import com.bumblebee.entities.User;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author numessi
 */
@Stateless
public class UserFacade implements UserFacadeLocal {

    @PersistenceContext(unitName = "resort-management-ejbPU")
    private EntityManager em;

    public void create(User user) {
        em.persist(user);
    }

    public void edit(User user) {
        em.merge(user);
    }

    public void remove(User user) {
        em.remove(em.merge(user));
    }

    public User find(Object id) {
        return em.find(User.class, id);
    }

    public User findLocalUser(String user_id, String location_id) {
        String query = "SELECT * FROM User " +
                "WHERE user_id='" +user_id+ "' AND user_location_id='"+location_id+"'";
        Query q = em.createNativeQuery(query, User.class);
        if (q.getResultList().isEmpty()) {
            return null;
        } else {
            return (User)q.getSingleResult();
        }
    }

    public List<User> findAll() {
        return em.createQuery("select object(o) from User as o").getResultList();
    }

    public List<User> findRange(int[] range) {
        Query q = em.createQuery("select object(o) from User as o");
        q.setMaxResults(range[1] - range[0]);
        q.setFirstResult(range[0]);
        return q.getResultList();
    }

    public int count() {
        return ((Long) em.createQuery("select count(o) from User as o").getSingleResult()).intValue();
    }

    public User login(String userName, String userPassword) {
        Query q = em.createQuery("SELECT object(o) FROM User AS o WHERE o.userId=?1 and o.userPassword=?2");
        q.setParameter(1, userName);
        q.setParameter(2, userPassword);
        try {
            return (User) q.getResultList().get(0);
        } catch (Exception ex) {
            return null;
        }

    }
}
